import webpack = require("webpack");
import gulp = require("gulp");
import fs = require("fs-extra");
// @ts-ignore
import gulpJson5 = require("gulp-json5-to-json");
// @ts-ignore
import gulpZip = require("gulp-zip");
// @ts-ignore
import gulpReplace = require("gulp-replace");
import webpackConfigs from "./webpack.config";
import { packageName } from "./tools";
import { destDir, pluginName } from "./config";

const cleanDist = () => fs.remove(destDir);

const runWebpack = async () =>
  new Promise((resolve, reject) => {
    // @ts-ignore
    webpack(webpackConfigs, (err, stats) => {
      if (err) {
        return reject(err);
      }
      if (stats && stats.hasErrors()) {
        stats.compilation.errors.forEach((item) => console.log(item.message));
        return reject(stats.compilation.errors);
      }
      resolve(stats);
    });
  });

const copyChromePluginPublicJsons = () =>
  gulp
    .src("./src/manifest.json")
    .pipe(gulpJson5({ beautify: false }))
    .pipe(gulpReplace('[VERSION]', process.env.npm_package_version))
    .pipe(gulpReplace('[NAME]', pluginName))
    .pipe(gulp.dest(destDir));

const compressChromePluginDir = () => {
  return gulp
    .src(`./${destDir}/**/*`)
    .pipe(gulpZip(packageName + ".zip"))
    .pipe(gulp.dest(destDir));
};

const compressChromePluginDir2 = () => {
  return gulp
    .src(`"./${destDir}/**/*"`)
    .pipe(gulpZip(packageName + "-chrome.zip.jpg"))
    .pipe(gulp.dest(destDir));
};

export default gulp.series(
  cleanDist,
  gulp.parallel(runWebpack, copyChromePluginPublicJsons),
  gulp.parallel(compressChromePluginDir /* , compressChromePluginDir2 */)
  // removeChromPluginDir
);
